<template>
  <view class="shoppingBox">
    <custom-navbar :immersive="true" title="社发配送" :showBack="false"> </custom-navbar>
    <view class="shoppingBox_header" :style="{ paddingTop: `${navbarHeight}px` }">
      <customerTab :items="items" :current="currentIndex" @changeTab="onClickItem"></customerTab>
    </view>

    <view class="shoppingBox_content">
      <view class="content">
        <scroll-view @scrolltolower="queryData" :scroll-top="scrollTop" :style="{ height: contentHeight + 'px' }" scroll-y="true" class="scroll-Y">
          <orderItem v-for="(item, index) in list" :key="index" :item="item" :index="index" @goDetail="onClickTo" @refundOrder="showRefundPop" @goShopping="goShopping" @goNavi="goNavi" @goPay="goPay"></orderItem>
        </scroll-view>
      </view>
    </view>

    <uni-popup ref="popup">
      <refundPop :item="selectOrder" @close="closeRefundPop" @submit="refundOrder"></refundPop>
    </uni-popup>
  </view>
</template>

<script>
import { getOrderList } from '@/service/api/personalCenter'

import { invalid } from '@/service/api/mine'
import { orderPay } from '@/service/api/wx'
import { getOpenId, getScreen, getUserInfo } from '@/service/auth'
import orderItem from '../components/orderItem'
import navbarMixin from '@/mxins/navbar.js'
import { orderList } from '@/service/api/orderquery'
import { format, now } from '@/utils/DateUtils.js'
import customerTab from '@/components/customerTab'
import { refundApply } from '@/service/api/refund'
import { refundPop } from '@/components/refundPop'
export default {
  components: { orderItem, customerTab, refundPop },
  mixins: [navbarMixin],
  data() {
    return {
      items: ['全部', '已支付', '已送货', '已验收', '已取消', '已退款'],
      current: 0,
      list: [],
      user: {},
      query: {
        page: 1,
        size: 20,
        customerIds: '',
        sort: 'id,desc',
      },
      orderStatus: '',
      isim: false,
      end: false,
      customerId: '',
      todayDate: '',
      contentHeight: '',
      currentIndex: 0,
      selectOrder: {},
    }
  },
  onLoad(option) {
    console.log('onLoad')
    this.customerId = option.customerId
    this.query.customerIds = this.customerId || this.user.customerIds
  },
  onShow() {
    const params = getApp().globalData.tabParams
    delete getApp().globalData.tabParams

    if (params) {
      this.onClickItem({ currentIndex: params.type })
    } else {
      this.onClickItem({ currentIndex: 0 })
    }
  },
  onPullDownRefresh() {
    this.init()
    this.onGet()
    uni.stopPullDownRefresh()
  },
  created() {
    const { width, height } = getScreen()
    this.contentHeight = height - (290 * width) / 750
    let user = getUserInfo()
    this.user = JSON.parse(user)

    console.log('contentHeight', this.contentHeight)
  },
  computed: {
    status() {
      return function (iStatus) {
        switch (iStatus) {
          case 'SAVE':
            return '保存'
          case 'PASS':
            return '审核'
          case 'CLOSED':
            return '关闭'
          default:
            return iStatus
        }
      }
    },
  },
  onReachBottom() {
    if (!this.end) {
      this.query.page += 1
      this.onGet()
    }
  },
  methods: {
    async onGet() {
      const _that = this
      try {
        uni.showLoading({
          title: '加载中',
        })
        orderList(this.query)
          .then(res => {
            uni.hideLoading()
            if (!res.data.content.length) return (this.end = true)
            res.data.content.forEach(item => {
              if (item.imageUrl) {
                let img = JSON.parse(item.imageUrl)
                item.imageUrl = img[0].path
              } else {
                item.imageUrl = 'https://www.zjjqf.cn/file/static/undefined.png'
              }
            })
            this.list.push(...res.data.content)
          })
          .catch(err => {
            uni.hideLoading()
            console.log('err', err)
            _that.uniShowToast(err.msg)
          })
      } catch (error) {
        uni.hideLoading()
      }
    },
    init() {
      this.query.page = 1
      this.list = []
      this.end = false
    },
    queryData() {
      console.log('queryData')
      if (this.end) return
      this.query.page++
      this.onGet()
    },

    onOpenDrawer() {
      this.$refs.showRight.open()
    },
    onSearch() {
      this.init()
      this.onGet()
      this.$refs.showRight.close()
    },
    onCancel() {
      this.$refs.showRight.close()
    },

    onClickTo(index) {
      uni.navigateTo({
        url: `/pages/mine/order/orderDetail?item=` + encodeURIComponent(JSON.stringify(this.list[index])),
      })
    },
    onClickItem(e) {
      console.log('e', e)
      switch (e.currentIndex) {
        case 0:
          //已支付
          delete this.query.orderStatus
          delete this.query.payStatus
          delete this.query.isAccept
          break
        case 1:
          //已支付
          this.query.orderStatus = 'SAVE'
          this.query.payStatus = '1'
          delete this.query.isAccept
          break
        case 2:
          //已发货
          this.query.orderStatus = 'CLOSE'
          this.query.payStatus = '1'
          delete this.query.isAccept
          break
        case 3:
          //已验收
          this.query.orderStatus = ''
          this.query.payStatus = ''
          this.query.isAccept = '1'

          break
        case 4:
          //已取消
          this.query.orderStatus = 'INVALID'
          this.query.payStatus = ''
          delete this.query.isAccept
          break
        case 5:
          //已取消
          this.query.payStatus = '2'
          this.query.orderStatus = ''
          delete this.query.isAccept
          break
      }

      this.currentIndex = e.currentIndex

      this.init()
      this.onGet()
    },
    refundOrder(currentReason) {
      uni.showLoading({ title: '提交中' })
      refundApply({ orderId: this.selectOrder.id, refundReason: currentReason })
        .then(res => {
          uni.hideLoading()
          if (res.status === 200) {
            this.closeRefundPop()
            this.init()
            this.onGet()
          } else {
            uni.showModal({ title: '提示', content: res.msg })
          }
        })
        .catch(err => {
          uni.hideLoading()
          uni.showModal({ title: '提示', content: err.msg })
        })
    },
    goShopping(index) {
      //再来一单，加入到购物车
      const order = this.list[index]
      const itemLists = order.detailList
      console.log('itemLists', itemLists)
      if (itemLists) {
        uni.setStorageSync('cartList', itemLists)
        const warehouseInfo = { code: order.warehouseCode, address: order.warehouseAddress, name: order.warehouseName, id: order.warehouseId }
        console.log('warehouseAddress', warehouseInfo)
        uni.setStorageSync('wareInfo', warehouseInfo)

        uni.navigateTo({ url: `/pageShopping/settlement/index` })
      } else {
        this.uniShowToast('暂无商品')
      }
    },
    showRefundPop(index) {
      this.selectOrder = this.list[index]
      this.$refs.popup.open()
    },
    closeRefundPop() {
      this.$refs.popup.close()
    },

    goNavi(index) {
      // 跳转到内置地图查看位置
      const order = this.list[index]
      if (order.warehouseLocation) {
        const lat = order.warehouseLocation.split(',')[1]
        const lng = order.warehouseLocation.split(',')[0]

        uni.openLocation({
          latitude: Number(lat), // 目标纬度
          longitude: Number(lng), // 目标经度
          name: order.warehouseName, // 位置名称
          address: order.warehouseAddress, // 详细地址
          success: () => console.log('跳转成功'),
          fail: err => {
            this.navigateToThirdPartyMap(Number(lat), Number(lng), order.warehouseName)
          },
        })
      } else {
        this.uniShowToast('暂无该地区地址信息')
      }
    },
    goPay(index) {
      const order = this.list[index]
      const _this = this
      orderPay({ orderId: order.orderId, openid: getOpenId() }).then(res1 => {
        //实名卡支付返回成功就是支付成功，其他支付再议
      })
    },
  },
}
</script>

<style lang="scss" scoped>
.shoppingBox {
  height: 100vh;
  background-color: #f6f6f6;
  display: flex;
  flex-direction: column;
  &_header {
    background-image: url('/static/image/order_head_bg.png');
    background-repeat: no-repeat;
    background-size: cover;
  }
  &_content {
    flex: 1;
    overflow: hidden;

    &_list {
      display: flex;
      position: relative;
      overflow-y: scroll;
      z-index: 1;
      &_left {
        width: 200rpx;
        background: #f5f6fa;
      }
      &_right {
        flex: 1;
      }
    }
  }
}
</style>
